/* eslint-disable react/jsx-no-undef */
/* eslint-disable @typescript-eslint/no-require-imports */
import React, { useState } from 'react'
import { ImageBackground, View, Text, StyleSheet, ScrollView, Dimensions, TouchableOpacity, PanResponder, Animated, FlatList, Modal, Pressable } from 'react-native'
import { Image as ExpoImage } from 'expo-image'
import { useNavigation } from '@react-navigation/native';
import ImageViewer from 'react-native-image-zoom-viewer';

const img = require('@/assets/images/1.png');
const real = require('@/assets/images/真人认证.png');
const back = require('@/assets/images/箭头.png');
const PathMap = require('@/assets/images/12.png')


const images = [
  { id: 1, source: 'https://picsum.photos/200?1' },
  { id: 2, source: 'https://picsum.photos/200?2' },
  { id: 3, source: 'https://picsum.photos/200?3' },
  { id: 4, source: 'https://picsum.photos/200?4' },
  { id: 5, source: 'https://picsum.photos/200?5' }
];

// 添加类型定义
type DetailsProps = {
  route: {
    params: {
      id: string;
    }
  }
}

// 1. 基础设置和状态管理
const { height } = Dimensions.get('window') // 获取设备屏幕尺寸

export default function Details({ route }: DetailsProps) {
  // 从路由参数中获取id
  const { id } = route.params;
  // console.log(id);

  const navigation = useNavigation();


  // 图片预览
  const [visible, setVisible] = useState(false);
  const [currentIndex, setCurrentIndex] = useState(0);
  const openImageViewer = (index: number) => {
    setCurrentIndex(index);
    setVisible(true);
  };

  // 创建三个动画值
  const marginTop = React.useRef(new Animated.Value(-120)).current;  // 控制内容区域上边距
  const imageScale = React.useRef(new Animated.Value(1)).current;    // 控制图片缩放
  const imageOpacity = React.useRef(new Animated.Value(1)).current;  // 控制图片透明度
  const controlsOpacity = React.useRef(new Animated.Value(1)).current; // 控制控制栏透明度
  

  const renderItem = ({ item, index }) => (
    <TouchableOpacity style={styles.imageContainer}>
      <Pressable onPress={() => openImageViewer(index)}>
        <ExpoImage source={{ uri: item.source }} style={styles.image} />
      </Pressable>
    </TouchableOpacity>
  );



  // 2. 手势控制系统
  const panResponder = React.useRef(
    PanResponder.create({
      onStartShouldSetPanResponder: () => true,  // 启用手势响应
      onPanResponderMove: (_, gestureState) => {
        // 向下滑动时
        if (gestureState.dy > 0) {
          // 限制上边距在 -120 到 0 之间
          const newMargin = Math.min(0, Math.max(-120, -120 + gestureState.dy));
          marginTop.setValue(newMargin);

          // 计算图片缩放值，最大放大到1.2倍
          const scale = 1 + Math.abs(gestureState.dy) / 500;
          imageScale.setValue(Math.min(1.2, scale));

          // 控制栏透明度变化
          const opacityDown = 1 - Math.abs(gestureState.dy) / 200;
          controlsOpacity.setValue(Math.max(0, opacityDown));
        }
        // 向上滑动时
        else if (gestureState.dy < 0) {
          // 限制上滑距离
          const newMargin = Math.max(-height + 100, -120 + gestureState.dy);
          marginTop.setValue(newMargin);

          // 逐渐降低图片透明度
          const opacity = 1 - Math.abs(gestureState.dy) / 200;
          imageOpacity.setValue(Math.max(0, opacity));

          // 控制栏透明度变化
          const opacityUp = 1 - Math.abs(gestureState.dy) / 200;
          controlsOpacity.setValue(Math.max(0, opacityUp));
        }
      },
      onPanResponderRelease: (_, gestureState) => {
        if (gestureState.dy < -100) {
          Animated.parallel([
            Animated.spring(marginTop, {
              toValue: -height + 100,
              useNativeDriver: false,
            }),
            Animated.spring(imageOpacity, {
              toValue: 0,
              useNativeDriver: false,
            }),
            Animated.spring(controlsOpacity, {
              toValue: 0,
              useNativeDriver: false,
            })
          ]).start();
        } else {
          Animated.parallel([
            Animated.spring(marginTop, {
              toValue: -120,
              useNativeDriver: false,
            }),
            Animated.spring(imageScale, {
              toValue: 1,
              useNativeDriver: false,
            }),
            Animated.spring(imageOpacity, {
              toValue: 1,
              useNativeDriver: false,
            }),
            Animated.spring(controlsOpacity, {
              toValue: 1,
              useNativeDriver: false,
            })
          ]).start();
        }
      },
    })
  ).current;

  return (
    <View style={{ flex: 1, backgroundColor: '#fff' }}>
      <ScrollView
        style={{ flex: 1 }}
        scrollEnabled={marginTop._value <= -120} // 只有当内容完全展开时才允许滚动
      >
        <View style={{ marginBottom: -20 }}>
          <Animated.View
            style={{
              opacity: imageOpacity,
              transform: [{
                scale: imageScale.interpolate({
                  inputRange: [1, 1.2],
                  outputRange: [1, 1.2]
                })
              }]
            }}
          >
            <ImageBackground
              style={{
                height: height / 2,
                width: '100%',
              }}
              source={img}
            >
              {/* real */}
              <TouchableOpacity style={{ position: 'absolute', top: 40, right: 5, transform: [{ rotate: '30deg' }] }}>
                <ExpoImage
                  source={real}
                  style={{ width: 75, height: 75 }}
                  contentFit="contain"
                />
              </TouchableOpacity>
              <View style={{
                flexDirection: 'row',
                justifyContent: 'space-between',
                padding: 15,
              }}>
                <TouchableOpacity
                  style={{
                    width: 32,
                    height: 32,
                    backgroundColor: 'rgba(0,0,0,0.3)',
                    borderRadius: 16,
                    justifyContent: 'center',
                    alignItems: 'center',
                  }}
                  onPress={() => navigation.goBack()}
                >
                  <ExpoImage
                    source={require('@/assets/images/backwhite.png')}
                    style={{ width: 16, height: 16 }}
                    contentFit="contain"
                  />
                </TouchableOpacity>

                <TouchableOpacity
                  style={{
                    width: 32,
                    height: 32,
                    backgroundColor: 'rgba(0,0,0,0.3)',
                    borderRadius: 16,
                    justifyContent: 'center',
                    alignItems: 'center',
                  }}
                >
                  <ExpoImage
                    source={require('@/assets/images/三个点.png')}
                    style={{ width: 16, height: 16 }}
                    contentFit="contain"
                  />
                </TouchableOpacity>
              </View>
            </ImageBackground>
          </Animated.View>
        </View>

        <Animated.View
          {...panResponder.panHandlers}
          style={[styles.infoContainer, {
            backgroundColor: '#fff',
            borderTopLeftRadius: 20,
            borderTopRightRadius: 20,
            marginTop: marginTop,
            minHeight: height // 确保内容区域至少有一个屏幕高度
          }]}
        >
          <View style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 15 }}>
            <Text style={styles.title}>丽丽</Text>
            <View style={{ flexDirection: 'row', marginLeft: 15 }}>
              <View style={styles.badge}>
                <ExpoImage
                  style={{ width: 16, height: 16 }}
                  contentFit="contain"
                />
              </View>
              <View style={[styles.badge, { marginLeft: 8 }]}>
                <ExpoImage
                  style={{ width: 16, height: 16 }}
                  contentFit="contain"
                />
              </View>
            </View>
          </View>

          <View style={styles.statsRow}>
            <Text style={styles.statsText}>关注 <Text style={{ color: '#000' }}>42</Text></Text>
            <Text style={styles.statsText}>粉丝 <Text style={{ color: '#000' }}>44</Text></Text>
          </View>
          <View style={styles.flexRow}>
            <Text style={styles.sectionTitle}>
              相册
            </Text>
            <TouchableOpacity onPress={() => navigation.navigate('photoAlbum')
            }>
              <ExpoImage style={{ width: 26, height: 26 }} source={back}></ExpoImage>
            </TouchableOpacity>
          </View>
          <FlatList
            data={images}
            renderItem={renderItem}
            keyExtractor={item => item.id.toString()}
            horizontal
            pagingEnabled
            style={{ marginBottom: 20 }}
            showsHorizontalScrollIndicator={false}
          />


          <Modal visible={visible} transparent={true}>
            <ImageViewer
              imageUrls={images.map(img => ({ url: img.source }))}
              index={currentIndex}
              onSwipeDown={() => setVisible(false)}
              enableSwipeDown={true}
              onClick={() => setVisible(false)}
              enablePreload={true}  // 开启预加载
              saveToLocalByLongPress={false}
            />
          </Modal>

          <Text style={styles.sectionTitle}>个人信息</Text>

          <View style={styles.infoGrid}>
            <View style={styles.infoItem}>
              <Text style={styles.infoLabel}>国家</Text>
              <Text style={styles.infoValue}>中国</Text>
            </View>
            <View style={styles.infoItem}>
              <Text style={styles.infoLabel}>语言</Text>
              <Text style={styles.infoValue}>中文（简体）</Text>
            </View>
            <View style={styles.infoItem}>
              <Text style={styles.infoLabel}>性别/年龄</Text>
              <Text style={styles.infoValue}>女/25</Text>
            </View>

            <View style={styles.infoItem}>
              <Text style={styles.infoLabel}>星座</Text>
              <Text style={styles.infoValue}>摩羯座</Text>
            </View>
            <View style={styles.infoItem}>
              <Text style={styles.infoLabel}>学历</Text>
              <Text style={styles.infoValue}>未知</Text>
            </View>
            <View style={styles.infoItem}>
              <Text style={styles.infoLabel}>职业</Text>
              <Text style={styles.infoValue}>未知</Text>
            </View>

            <View style={[styles.infoItem, { width: '100%' }]}>
              <Text style={styles.infoLabel}>城市</Text>
              <Text style={styles.infoValue}>未知</Text>
            </View>
          </View>

          <Text style={[styles.sectionTitle, { marginTop: 20 }]}>聊友足迹</Text>
          <View style={styles.mapContainer}>
            <ExpoImage
              style={styles.worldMap}
              contentFit="cover"
              source={PathMap}
            />
          </View>

        </Animated.View>
      </ScrollView>

      {/* 将控制栏移到 ScrollView 外部，确保它始终可见 */}
      <Animated.View style={[styles.mapControls, {
        position: 'absolute',
        bottom: 20,
        left: 0,
        right: 0,
        opacity: controlsOpacity
      }]}>
        <TouchableOpacity style={styles.mapArrow}>
          <ExpoImage
            style={{ width: 20, height: 20,transform: [{ rotate: '180deg' }] }}
            source={require('@/assets/images/箭头.png')}
          />
        </TouchableOpacity>
        <View style={styles.chatButton}>
        <Text style={styles.chatText}>Mess</Text>
        </View>
        <View style={styles.chatBubble}>
          <Text style={styles.chatText}>Hi</Text>
        </View>
        <TouchableOpacity style={styles.mapArrow}>
          <ExpoImage
            style={{ width: 20, height: 20 }}
            source={require('@/assets/images/箭头.png')}
          />
        </TouchableOpacity>
      </Animated.View>
    </View>
  )
}

// 3. 样式定义示例
const styles = StyleSheet.create({
  infoContainer: {
    padding: 20,
  },
  flexRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  imageContainer: {
    marginHorizontal: 10,
  },
  image: {
    width: 100,
    height: 100,
    borderRadius: 10,
  },
  title: {
    fontSize: 22,
    fontWeight: 'bold',
  },
  badge: {
    width: 32,
    height: 32,
    borderRadius: 16,
    backgroundColor: '#f5f5f5',
    justifyContent: 'center',
    alignItems: 'center',
  },
  statsRow: {
    flexDirection: 'row',
    marginBottom: 25,
  },
  statsText: {
    marginRight: 20,
    color: '#666',
    fontSize: 14,
  },
  sectionTitle: {
    fontSize: 16,
    fontWeight: '600',
    marginBottom: 15,
  },
  // 网格布局相关样式
  infoGrid: {
    flexDirection: 'row',    // 水平排列
    flexWrap: 'wrap',       // 允许换行
    justifyContent: 'space-between', // 两端对齐
  },
  infoItem: {
    width: '48%',  // 设置为接近半宽，留出间距
    backgroundColor: '#f8f8f8',
    padding: 12,
    borderRadius: 10,
    marginBottom: 12,
  },
  infoLabel: {
    color: '#999',
    fontSize: 13,
    marginBottom: 4,
  },
  infoValue: {
    fontSize: 14,
    color: '#333',
  },
  mapContainer: {
    height: 220,
    borderRadius: 15,
    overflow: 'hidden',
    backgroundColor: '#e8f7f7',
    padding:10,
  },
  worldMap: {
    width: '100%',
    height: '100%',
  },
  mapControls: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 15,
    backgroundColor: 'transparent'
  },
  mapArrow: {
    width: 36,
    height: 36,
    backgroundColor: 'rgba(0,0,0,0.3)',
    borderRadius: 18,
    justifyContent: 'center',
    alignItems: 'center',
  },
  chatButton: {
    width: 44,
    height: 44,
    backgroundColor: 'rgba(0,0,0,0.6)',
    borderRadius: 22,
    justifyContent: 'center',
    alignItems: 'center',
  },
  chatBubble: {
    backgroundColor: 'rgba(0,0,0,0.6)',
    paddingHorizontal: 15,
    paddingVertical: 8,
    borderRadius: 20,
  },
  chatText: {
    color: '#fff',
    fontSize: 14,
  },
});
